<template>
  <div class="technical_confirm">
    <one-title title="生产技术状态确认" @refreshData="refresh">
      <div class="mes_btn">
        <span class="download_btn" @click="downParamTemplate">参数模板下载</span>
        <disabled-btn
          v-btn-permission="'downTemplate'"
          :judge="showImportJudge"
          iconClass="iconfont icon-download"
          btnText="参数记录表下载"
          @judgeClick="downTemplate"></disabled-btn>
        <disabled-btn
          v-btn-permission="'importJudge'"
          :judge="showImportJudge"
          iconClass="iconfont icon-btn_import"
          btnText="导入参数记录表"
          @judgeClick="showImport"></disabled-btn>
        <!--<el-button :disabled="true">-->
        <!--<i class="iconfont icon-tongbu"></i>-->
        <!--同步最新工艺-->
        <!--</el-button>-->
        <el-button
          v-btn-permission="'dataInherit'"
          @click="dataInherit">
          <i class="iconfont icon-jichengxianyou"></i>
          继承现有
        </el-button>
        <el-button
          v-btn-permission="'submit'"
          @click="handleSubmit" type="success">
          <i class="iconfont icon-btn_addnew"></i>
          提交确认
        </el-button>
      </div>
    </one-title>
    <div class="task_tree_container">
      <task-bom-tree ref="taskBomTree" @selectNode="selectNode"></task-bom-tree>
      <div class="task_tree_content">
        <assign-rule ref="assignRule" @submitSuccess="getChildList"></assign-rule>
        <q-time-rule ref="qTimeRule" @submitSuccess="getChildList"></q-time-rule>
        <spare-ratio ref="spareRatio" @submitSuccess="getChildList"></spare-ratio>
        <error-check :title="`提交确认`" ref="errorCheck"></error-check>
        <check-row-dialog ref="checkRowDialog"></check-row-dialog>
        <div class="base_list">
          <mes-search-comp
            :searchList="searchList"
            @searchInfo="_info"
            :searchResult="searchResult"
            :showSlotSet="true"
            @setCol="$refs.ColumnControl.openDialog()"
            ref="mesSearch">
          </mes-search-comp>
          <div class="table_container">
            <el-table
              ref="tableNode"
              :data="listData.list"
              border
              stripe
              v-loading="isLoading1"
              :max-height="250"
              :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
              @row-click="(row) => $refs.tableNode.toggleRowSelection(row)"
              @sort-change="_sort"
              @filter-change="handleFilterChange"
              @selection-change="handleSelectionChange">
              <el-table-column
                fixed="left"
                width="40"
                type="selection"
                align="center">
              </el-table-column>
              <mes-col-comp
                :key="index"
                v-for="(column, index) in columnList"
                :column="column">
              </mes-col-comp>
              <el-table-column
                fixed="right"
                :resizable="false"
                min-width="88"
                label="操作"
                class-name="operation_btn"
                align="center">
                <template slot-scope="scope">
                  <!--<span class="jump_item" @click.stop="checkRow(scope.row.id)">条件检查</span>-->
                  <span class="jump_item" @click.stop="showLog(scope.row)">操作记录</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <mes-pagination
            @updateData="init"
            :currentPage="listData.pageNo"
            :total="listData.count || 0"
            :pageSize="listData.pageSize">
          </mes-pagination>
        </div>
        <div class="detail_list" v-if="selectData.length === 1">
          <div class="mes_btn btn_list" v-if="selectData.length <= 1">
            <el-button
              v-btn-permission="'spareRatio'"
              @click="openSpareRatio">
              <i class="iconfont icon-beifenliangxishu"></i>
              备份量系数
            </el-button>
            <el-button
              v-btn-permission="'qTimeRule'"
              @click="openQTimeRule">
              <i class="iconfont icon-shezhiqtime"></i>
              设置Q'Time
            </el-button>
            <el-button
              v-btn-permission="'assignRule'"
              @click="openAssignRule">
              <i class="iconfont icon-btn_edit"></i>
              设置派工规则
            </el-button>
            <el-button
              v-btn-permission="'editProcess'"
              @click="editProcess">
              <i class="iconfont icon-btn_addnew"></i>
              编辑工艺路线
            </el-button>
          </div>
          <el-tabs v-model="tabsValue" type="border-card" v-loading="isLoading2" class="mes_tabs">
            <el-tab-pane label="工序" name="first">
              <div class="table_panel table_container tab_pane">
                <el-table
                  class="table_dialog"
                  :data="workStageList"
                  border
                  :max-height="tableCascadeHeight"
                  style="width: 100%"
                  tooltip-effect="dark"
                  stripe>
                  <mes-col-comp :key="index + '1'" v-for="(column, index) in childList.workstageCol1"
                                :column="column"></mes-col-comp>
                  <el-table-column
                    prop="qtimeString"
                    label="QTime"
                    width="120"
                    show-overflow-tooltip
                    align="center">
                    <template slot-scope="scope">
                      <span>{{stringifyQTime(scope.row)}}</span>
                    </template>
                  </el-table-column>
                  <mes-col-comp :key="index + '2'" v-for="(column, index) in childList.workstageCol2"
                                :column="column"></mes-col-comp>
                  <el-table-column
                    show-overflow-tooltip
                    prop="workstageRemarks"
                    :resizable="false"
                    align="center"
                    min-width="95"
                    label="参数记录表"
                    fixed="right">
                    <template slot-scope="scope">
                      <span v-if="!scope.row.paramTemplateId" class="jump_item is_success"
                            @click="openProcessTemplate(scope.row, true)">
                        新增
                      </span>
                      <span v-else class="jump_item"
                            @click="openProcessTemplate(scope.row, false)">详情</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="工序上料清单" name="second">
              <div class="table_panel table_container tab_pane">
                <el-table
                  :data="workorderWorkstageMaterialList"
                  :max-height="tableCascadeHeight"
                  border
                  stripe
                  style="width: 100%; margin-top: 20px">
                  <mes-col-comp :key="index" v-for="(column, index) in childList.workstageMateriel"
                                :column="column"></mes-col-comp>
                </el-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="制造资源清单" name="third">
              <div class="table_panel table_container tab_pane">
                <el-table
                  :data="workorderWorkstageResourceList"
                  :max-height="tableCascadeHeight"
                  border
                  stripe
                  style="width: 100%; margin-top: 20px">
                  <mes-col-comp :key="index" v-for="(column, index) in childList.resourcesList"
                                :column="column"></mes-col-comp>
                </el-table>
              </div>
            </el-tab-pane>
            <el-tab-pane label="设备信息" name="five">
              <div class="table_panel table_container tab_pane">
                <el-table
                  :data="deviceMsg"
                  :max-height="tableCascadeHeight"
                  border
                  stripe
                  style="width: 100%; margin-top: 20px">
                  <mes-col-comp :key="index" v-for="(column, index) in childList.deviceMsg"
                                :column="column"></mes-col-comp>
                </el-table>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <!--参数模板导入-->
    <import-param ref="ImportParam"
                  @refresh="init(listData)"></import-param>
    <!--参数模板-->
    <process-template ref="ProcessTemplate" @success="getChildList"></process-template>
    <!-- 日志详情 -->
    <log-detail ref="logDetail"></log-detail>
    <!--继承现有弹窗-->
    <inherit-dialog ref="inheritDialog"></inherit-dialog>
    <!--列隐藏-->
    <column-control
      ref="ColumnControl"
      :colList="searchList"
      @saveCol="saveCol"
    ></column-control>
  </div>
</template>

<script>
import TreeFlodBtn from '@/components/TreeFlodBtn'
import {AssignRule, CheckRowDialog, QTimeRule, SpareRatio} from './components'
import {BoolType} from '@/components/mesDict'
import ErrorCheck from '../../../../components/ErrorCheck'
import searchList from './baseList'
import childList from './childList'
import ImportParam from './components/ImportParam'
import InheritDialog from './components/InheritDialog'
import {ProcessTemplate} from '../../../../components/Template'

export default {
  name: 'TechnicalConfirm',
  components: {
    ErrorCheck,
    QTimeRule,
    SpareRatio,
    AssignRule,
    BoolType,
    TreeFlodBtn,
    ImportParam,
    CheckRowDialog,
    ProcessTemplate,
    InheritDialog
  },
  data() {
    return {
      childList: childList, // 子列表
      selectData: [], // 选择的列表
      searchResult: NaN, // 搜索结果数
      tabsValue: 'first', // tabs组件value值
      isLoading1: false, // 主列表数据是否在加载
      isLoading2: false, // 工序子表加载状态
      searchData: {}, // 搜索列表数据
      sortData: {}, // 排序字段
      workStageList: [], // 工序列表
      treeClose: false,
      taskNumber: '', // 当前任务号
      workorderIds: [], // 树返回的工单ID数组
      checkedKeys: window.localStorage.getItem(this.$route.name), // 显示的列集合
      isInheritEnd: true, // 是否继承完毕
    }
  },
  computed: {
    // 获取列表数据
    listData() {
      return this.$store.state.technicalConfirm.listData
    },
    // 导入参数列表是否可用
    showImportJudge() {
      if (this.workorderIds.length) {
        return {msg: '请先选中左侧生产任务号！', disabled: true}
      } else if (!this.taskNumber) {
        return {msg: '请先选中左侧生产任务号！'}
      }
      return {msg: false}
    },
    // 检查结果
    checkData() {
      return this.$store.state.technicalConfirm.checkData
    },
    // 获取子列表数据
    detailListData() {
      return this.$store.state.technicalConfirm.detailListData
    },
    // 物料清单
    workorderWorkstageMaterialList() {
      return this.detailListData.workorderWorkstageMaterialList || []
    },
    // 资源清单
    workorderWorkstageResourceList() {
      return this.detailListData.workorderWorkstageResourceList || []
    },
    // 设备信息
    deviceMsg() {
      return this.detailListData.device || []
    },
    // 除去"待下发"进度状态列表
    partWorkorderProcessStatus() {
      let list = this.$store.state.dict.workorderProcessStatus.labels || []
      return list.filter(item => item.value !== 'ToBeAssigned')
    },
    // 除去"待下发"进度状态id
    partWorkorderProcessStatusId() {
      return this.partWorkorderProcessStatus.reduce((pre, cur) => [...pre, cur.id], []).join(',')
    },
    searchList,
    // 列循环
    columnList() {
      this.$nextTick(() => {
        this.$refs.tableNode.doLayout()
      })
      let checkedKeysList = this.checkedKeys ? JSON.parse(this.checkedKeys) : this.searchList.reduce((pre, cur) => [...pre, cur.prop], [])
      return this.searchList.filter(item => item.noForCol !== true && (item.noChecked === true || checkedKeysList.some(key => key === item.prop)))
    },
  },
  mounted() {
    this.$refs.taskBomTree.init()
    this.init()
  },
  activated() {
    // 从编辑工艺页面返回时刷新工艺
    if (this.$route.query && this.$route.query.callback === '1') {
      this.getChildList()
    }
  },
  methods: {
    // 列筛选回调
    handleFilterChange(filters) {
      this.sortData = {}
      this.$refs.tableNode.clearSort()
      let filterParams = this.$filterParams(this.searchList, filters)
      Object.assign(this.searchData, filterParams.search)
      Object.assign(this.sortData, filterParams.order)
      this.init()
    },
    // 修改列显示
    saveCol(checkedKeys) {
      this.checkedKeys = checkedKeys
    },
    // 选择文件
    showImport() {
      if (this.taskNumber) this.$refs.ImportParam.openDialog(this.taskNumber)
    },
    // 下载参数记录表
    downTemplate() {
      if (!this.taskNumber) return
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workstagerecordtemplate/workstageRecordTemplate/download',
        data: {taskNumber: this.taskNumber},
        responseType: 'blob',
        noCommit: true
      }).then((res) => {
        this.$downFile(res, `参数记录表${this.taskNumber}.zip`)
      })
    },
    // 下载参数模板
    downParamTemplate() {
      this.$downByBlob('', '参数记录模板.xls', 'a/workorder/workorder/downloadparamtertemplate')
    },
    // 编辑参数记录模板
    openProcessTemplate(row, type) {
      let obj = {
        // 物料名称
        materialName: this.selectData[0].materialName,
        // 工序名称
        workstageName: row.workstageName,
        // 工序编号
        workstageNumber: row.workstageNumber,
        // 工序Id
        workstageId: row.id,
        // 批次类型
        entry: 'workorder',
        // 是否新增
        isNew: type
      }
      this.$refs.ProcessTemplate.openDialog(obj)
    },
    // 显示日志
    showLog(row) {
      this.$refs.logDetail.openDialog({
        title: '工单编号',
        name: row.number,
        url: 'a/workorderstatuschangehistory/workorderStatusChangeHistory/list',
        query: {
          workorderId: row.id
        }
      })
    },
    checkSelect() {
      let flag = true
      if (this.selectData.some(item => item.workorderProcessStatusValue !== 'ToBeConfirmed')) {
        this.$message.error({
          message: '只有工单进度为待确认的可以提交确认',
          duration: 1500,
          center: true
        })
        flag = false
      }
      if (this.selectData.some(item => item.statusValue !== 'Normal')) {
        this.$message.error({
          message: '只有工单状态为正常的可以提交确认',
          duration: 1500,
          center: true
        })
        flag = false
      }
      return flag
    },
    // 单行检查
    checkRow(id) {
      this.$refs.checkRowDialog.openDialog(id)
    },
    // 获取选中的ID数组
    getSelectIDs() {
      return this.selectData.reduce((pre, cur) => [...pre, cur.id], [])
    },
    handleSubmit() {
      if (!this.selectData.length) {
        return this.tipMessage('error', '请选择一条工单进行操作')
      }
      if (!this.checkSelect()) return
      let commitObj = {
        method: 'post',
        url: 'a/workorder/workorder/submitConfirm',
        data: {
          ids: this.getSelectIDs().toString()
        },
        noCommit: true
      }
      this.$store.dispatch('saveData', commitObj).then(res => {
        if (res.data.errMessages) {
          return this.$refs.errorCheck.openDialog(res.data.errMessages)
        }
        this.saveSuccess()
        this.init()
      })
    },
    saveSuccess() {
      this.$message.success({
        message: '保存成功',
        duration: 1500,
        center: true,
      })
    },
    // 编辑工艺路线
    editProcess() {
      this.$router.push({
        path: 'confirmProcess',
        query: {
          id: this.selectData[0].id,
        }
      })
    },
    // 编辑派工规则
    openAssignRule() {
      let id = this.selectData[0].id
      this.$refs.assignRule.openDialog(id)
    },
    // 编辑QTime
    openQTimeRule() {
      let id = this.selectData[0].id
      this.$refs.qTimeRule.openDialog(id)
    },
    // 备份量系数
    openSpareRatio() {
      let id = this.selectData[0].id
      this.$refs.spareRatio.openDialog(id)
    },
    // 刷新方法
    refresh() {
      this.taskNumber = ''
      this.workorderIds = []
      this.$refs.taskBomTree.init()
      this.$refs.mesSearch.clean()
      this.$refs.tableNode.clearSort()
      this.$refs.tableNode.clearFilter()
      this.sortData = {}
      this.searchData = {}
      this.init()
    },
    // 选择树形节点
    selectNode(taskNumber, workorderIds) {
      this.searchData = {}
      this.taskNumber = taskNumber
      this.workorderIds = workorderIds
      this.$refs.mesSearch.clean()
      this.init()
    },
    // 主列表获取
    init(page) {
      this.isLoading1 = true
      let postData = {
        method: 'post',
        url: 'a/workorder/workorder/list',
        data: {
          pageNo: page ? page.pageNo : 1,
          pageSize: page ? page.pageSize : this.listData.pageSize || 15,
          query: {
            columns: this.searchList.reduce((pre, cur) => [...pre, cur.prop], []),
            ...this.searchData,
            viewSource: 2
          }, // viewSource 视图来源，2表示生产确认
          sort: this.sortData
        },
        module: 'technicalConfirm',
        state: 'listData'
      }
      if (!postData.data.query.workorderProcessStatusId) {
        postData.data.query.workorderProcessStatusId = this.partWorkorderProcessStatusId
      }
      if (this.taskNumber) {
        postData.data.query.taskNumber = this.taskNumber
      }
      if (this.workorderIds.length) {
        postData.data.query.id = this.workorderIds.toString()
      }
      this.$store.dispatch('saveData', postData).then((res) => {
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
      }).then(() => {
        let list = this.listData.list || []
        if (list.length) {
          this.tableDefaultSelect(list[0])
        }
      }).finally(() => {
        this.isLoading1 = false
      })
    },
    // 查询
    _info(data) {
      this.searchData = data
      this.$refs.tableNode.clearSort()
      this.$refs.tableNode.clearFilter()
      this.sortData = {}
      this.init()
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    // 多选表格数据
    handleSelectionChange(val) {
      this.selectData = val
      if (this.selectData.length === 1) {
        this.getChildList()
      }
    },
    // 表格默认选择
    tableDefaultSelect(item) {
      this.selectData = [item]
      this.$refs.tableNode.toggleRowSelection(item, true)
    },
    /**
     * 解析工序子列表
     */
    parseChildList(obj) {
      this.workStageList = obj ? obj.workorderWorkstageList || [] : []
    },
    /**
     * 获取工序子列表
     */
    getChildList() {
      if (this.selectData.length !== 1) return
      let id = this.selectData[0].id
      this.tabsValue = 'first'
      this.isLoading2 = true
      this.parseChildList(null)
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/workorder/workorder/getworkorderwithdevice',
        data: {
          workorderId: id
        },
        module: 'technicalConfirm',
        state: 'detailListData'
      }).then((res) => {
        this.parseChildList(res)
      }).finally(() => {
        this.isLoading2 = false
      })
    },
    // 拼接QTime
    stringifyQTime(row) {
      if (row.qtimeRule !== undefined && row.qtimeString !== undefined) {
        return row.qtimeRule + row.qtimeString.replace(',', '')
      }
    },
    // 继承现有数据
    dataInherit() {
      if (!this.taskNumber) {
        return this.tipMessage('error', '请先选择任务号')
      }
      this.mesConfirm('是否继承现有技术状态?', '提示').then(() => {
        let inheritToken = this.$axios.CancelToken.source()
        this.isInheritEnd = false
        let seconds = 0
        let times = setInterval(() => {
          seconds = seconds + 1
          if (seconds >= 1 && !this.isInheritEnd) {
            this.$refs.inheritDialog.openDialog(inheritToken)
          }
        }, 1000)
        this.$store.dispatch('saveData', {
          method: 'post',
          url: 'a/workorder/workorder/inheritData',
          data: {taskNumber: this.taskNumber},
          cancelToken: inheritToken.token,
          noCommit: true
        }).then(() => {
          this.tipMessage('success', '继承现有数据成功!')
          this.init()
        }).finally(() => {
          this.isInheritEnd = true
          clearInterval(times)
          this.$refs.inheritDialog.dialogVisible = false
        })
      })
    },
    /**
     * 提示
     * @param type 提示类型
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .technical_confirm {
    .download_btn {
      color: @mesFontBlue;
      font-size: 14px;
      padding-right: 10px;
      cursor: pointer;
      &:hover {
        color: darken(@mesFontBlue, 5%);
      }
      &:active {
        color: darken(@mesFontBlue, 10%);
      }
    }
    height: 100%;
    .el-tabs--border-card > .el-tabs__header {
      margin-bottom: 20px !important;
    }
    .icon-btn_Save {
      color: @btnAddBgC;
    }

    .icon-tab_close_n {
      color: @btnDeleteBgC;
    }
    .jump_item {
      .iconfont {
        font-size: 13px;
      }
    }
    .upload_btn {
      position: relative;
      overflow: hidden;
      margin-right: 10px;
      .file_btn {
        position: absolute;
        top: -20px;
        left: -20px;
        right: -20px;
        bottom: -20px;
        opacity: 0;
        cursor: pointer;
      }
    }
    .detail_list {
      position: relative;
      padding: 10px 20px 40px 20px;
      .btn_list {
        position: absolute;
        top: 10px;
        right: 20px;
        z-index: 10;
      }
      .table_panel {
        padding: 0 !important;
        .el-tabs__header {
          margin-bottom: 0;
        }
        .el-table--border {
          margin: 0 !important;
          .el-table-column--selection .cell {
            padding: 0;
          }
        }
      }
    }
  }
</style>
